package cn.jeeweb.web.modules.sys.controller;

import cn.jeeweb.common.utils.FastJsonUtils;
import cn.jeeweb.web.aspectj.annotation.Log;
import cn.jeeweb.web.modules.sys.entity.Dict;
import cn.jeeweb.web.modules.sys.service.IDictService;
import cn.jeeweb.common.http.Response;
import cn.jeeweb.common.mvc.annotation.ViewPrefix;
import cn.jeeweb.common.mvc.controller.BaseBeanController;
import cn.jeeweb.common.mybatis.mvc.wrapper.EntityWrapper;
import cn.jeeweb.common.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.common.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jeeweb.common.utils.StringUtils;
import cn.jeeweb.web.utils.DictUtils;
import cn.jeeweb.web.utils.PageRequest;
import cn.xjzn.framework_Core.ModuleActionType;
import com.baomidou.mybatisplus.plugins.Page;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.List;

/**
 * @package cn.jeeweb.web.modules.sys.controller
 * @title: 消息模版控制器
 * @description: 消息模版控制器
 */

@RestController
@RequestMapping("/sys/dict")
@ViewPrefix("modules/sys/dict")
@RequiresPathPermission("sys:dict")
@Log(title = "字典管理")
public class DictController extends BaseBeanController<Dict> {

	@Autowired
	private IDictService dictService;

	/**
	 * 字典
	 * @return
	 */
	@GetMapping(value = "")
	public Response get() {
		Response response = new Response();
		try {
			//放入数据字典
			response.putObject(DictUtils.getDict());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error("获取失败");
		}
		return response;
	}
	/**
	 * 根据页码和每页记录数，以及查询条件动态加载数据
	 *
	 * @param request
	 * @throws IOException
	 */
	@GetMapping(value = "list")
	@Log(logType = ModuleActionType.SELECT)
	@RequiresMethodPermissions("list")
	public void list( HttpServletRequest request) throws IOException {
		//加入条件
		EntityWrapper<Dict> entityWrapper = new EntityWrapper<>(Dict.class);
		entityWrapper.orderBy("sort",true);
		String keyword=request.getParameter("keyword");
		String gid=request.getParameter("gid");
		if (!StringUtils.isEmpty(gid)&&!StringUtils.isEmpty(keyword)){
			entityWrapper.eq("gid",gid).andNew().like("label",keyword).or().like("value",keyword);
		}else if(!StringUtils.isEmpty(gid)){
			entityWrapper.eq("gid",gid);
		}
		entityWrapper.ne("visible","0");

		// 预处理
		Page pageBean = dictService.selectPage(PageRequest.getPage(),entityWrapper);
		FastJsonUtils.print(pageBean);
//		return Response.ok(null,pageBean);
	}

	@PostMapping("add")
	@Log(logType = ModuleActionType.INSERT)
	@RequiresMethodPermissions("add")
	public Response add(Dict entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		Dict old = null;
		EntityWrapper<Dict> entityWrapper = new EntityWrapper<Dict>(entityClass);
		entityWrapper.eq("gid",entity.getGid());
		entityWrapper.eq("label",entity.getLabel());
		old = dictService.selectOne(entityWrapper);
		if(old == null){
			EntityWrapper<Dict> entityWrapper_ = new EntityWrapper<Dict>(entityClass);
			entityWrapper_.eq("gid",entity.getGid());
			entityWrapper_.eq("value",entity.getValue());
			old = dictService.selectOne(entityWrapper_);
			if(old != null){
				return Response.error("保存失败，同一分组字典值已存在");
			}else{
				try{
					dictService.insert(entity);
				}catch (Exception e){
					return Response.error("保存失败，请联系管理员");
				}
			}
			return Response.ok("添加成功");
		}else{
			return Response.error("保存失败，同一分组字典显示文字已存在");
		}
	}

	@PostMapping("{id}/update")
	@Log(logType = ModuleActionType.UPDATE)
	@RequiresMethodPermissions("add")
	public Response update(Dict entity, BindingResult result,
						   HttpServletRequest request, HttpServletResponse response) {
		// 验证错误
		this.checkError(entity,result);
		Dict old = null;
		EntityWrapper<Dict> entityWrapper = new EntityWrapper<Dict>(entityClass);
		entityWrapper.eq("gid",entity.getGid());
		entityWrapper.eq("label",entity.getLabel());
		old = dictService.selectOne(entityWrapper);
		if(old != null && !old.getId().equals(entity.getId())){
			return Response.error("保存失败，同一分组字典显示文字已存在");
		}else{
			EntityWrapper<Dict> entityWrapper_ = new EntityWrapper<Dict>(entityClass);
			entityWrapper_.eq("gid",entity.getGid());
			entityWrapper_.eq("value",entity.getValue());
			old = dictService.selectOne(entityWrapper_);
			if(old != null && !old.getId().equals(entity.getId())){
				return Response.error("保存失败，同一分组字典值已存在");
			}else{
				try{
					dictService.insertOrUpdate(entity);
				}catch (Exception e){
					return Response.error("保存失败");
				}
			}
			return Response.ok("更新成功");
		}
	}

	@PostMapping("{id}/delete")
	@Log(logType = ModuleActionType.DELETE)
	public Response delete(@PathVariable("id") String id) {
		dictService.deleteById(id);
		return Response.ok("删除成功");
	}

	@PostMapping("batch/delete")
	@Log(logType = ModuleActionType.DELETE)
	@RequiresMethodPermissions("delete")
	public Response batchDelete(@RequestParam("ids") String[] ids) {
		List<String> idList = java.util.Arrays.asList(ids);
		dictService.deleteBatchIds(idList);
		return Response.ok("删除成功");
	}


//	@RequestMapping(value = "/upload", method = RequestMethod.POST) 晓恩，
//	public Response upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
//		try {
//			//信息返回
//			String result = "";
//			long fileSize = file.getSize();
//			StringBuffer message = new StringBuffer();
//			Workbook workbook = null;
//			UsbkeyInfo usbkeyInfoExcel = null;
//			InputStream in = file.getInputStream();
//			workbook = Workbook.getWorkbook(in);
//			Sheet sheet = workbook.getSheet(0);// 选取excel中的第一页
//			int rows = sheet.getRows();// 得到此页的行(不要设置状态列的上传否则管理混乱)
//			int cols = sheet.getColumns();// 得到此页的列(以实际设定的列数为准)
//			for (int row = 2; row <= rows; row++) {
//				String val1 = sheet.getCell(0, row).getContents();//编码
//				String val2 = sheet.getCell(1, row).getContents();//文字描述
//				if (val1.equals("") && val2.equals("")) {
//					rows = rows - 1;
//				}
//			}
//			if (rows > 0 && cols == 4) {
//				//导入成功条数
//				int successCount = 0;
//				//导入失败条数
//				int errorCount = 0;
//				for (int j = 2; j <= rows - 1; j++) {
//					usbkeyInfoExcel = new UsbkeyInfo();
//					String errorinfo = "";
//					for (int i = 1; i <= 3; i++) {
//						String content = sheet.getCell(i, j).getContents();
//						if (StringUtils.isEmpty(content)) {
//							if (i == 1) {
//								errorinfo += "USBKEY令牌名为空；";
//							} else if (i == 2) {
//								errorinfo += "USBKEY序列号为空；";
//							} else {
//								errorinfo += "USBKEY型号为空；";
//							}
//						} else {
//							if (i == 2) {
//								//查询该key是否在系统中存在
//								List<UsbkeyInfo> usbkeyinfos = usbkeyInfoService.getUsbkeyInfos(content.trim());
//								if(usbkeyinfos.size()>0){
//									errorinfo += "USBKEY序列号：" + content + "系统中已经存在；";
//									break;
//								}else{
//									usbkeyInfoExcel.setUsbkeyCode(content);//设置编号
//								}
//
//							} else if (i == 3) {
//								String keyType = SystemUsbkeyConfigUtils.getSystemUsbkeyByName(content.trim());
//								if (keyType != null) {
//									usbkeyInfoExcel.setUsbkeyType(keyType);//设置型号
//								} else {
//									errorinfo += "USBKEY型号:" + content + "不存在；";
//								}
//							} else if (i == 1) {
//								usbkeyInfoExcel.setUsbkeyName(content);
//							}
//						}
//					}
//					if (!ConstData.isEmpty(errorinfo)) {
//						errorCount = errorCount + 1;
//						//暂时不列举失败详情
////                        int count = j+1;
////                        message.append("第" + count + "行" + errorinfo + "<br/>");
//					} else {
//						usbkeyInfoExcel.setOperateTime(new Timestamp((DateUtil.string2Date(operateTime, "yyyy-MM-dd")).getTime()));//yyyy-MM-dd HH:mm:ss
//						String companyId = SystemConfigUtils.getSystemConfigStr("sysCompanyId");
//						System.out.println("companyId:" + companyId);
//						usbkeyInfoExcel.setCompanyId(SystemConfigUtils.getSystemConfigStr("sysCompanyId"));
//						usbkeyInfoExcel.setUsbkeyStatus(Global.USBKEY_STATUS_WXF);//设置状态
//						usbkeyInfoService.saveUsbkeyInfoExcel(usbkeyInfoExcel);
//						successCount = successCount + 1;
//					}
//				}
//				workbook.close();
//				result = "已成功导入"+successCount+"条数据；";
////                if(!StringUtils.isEmpty(message.toString())){
//				result = result +"导入失败"+errorCount+"条数据；";
////                }
//				response.setContentType("text/html;charset=UTF-8");
//				response.getWriter().print(alertAndRedirect(result));
//			} else {
//				result = alertAndRedirect("导入Excel文档模板错误");
//				response.setContentType("text/html;charset=UTF-8");
//				response.getWriter().print(result);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}null

}